package com.dlyk.config.handler;

import com.dlyk.result.CodeEnum;
import com.dlyk.result.R;
import com.dlyk.util.JSONUtils;
import com.dlyk.util.ResponseUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 访问拒绝处理器（没有权限访问时的处理器）
 */
@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {

    // 注意：如果配置了全局异常处理器，则会被全局异常处理器拦截并处理，就不会执行下面这个方法

    // 没有权限访问时，就执行该方法，在该方法中返回json给前端
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {

        // 响应结果对象
        R result = R.FAIL(CodeEnum.ACCESS_DENIED);
        // 将响应结果对象转换为JSON字符串
        String resultJson = JSONUtils.toJSON(result);
        // 响应给前端
        ResponseUtils.write(response, resultJson);
    }

}

